package logger

import (
	"errors"
	"fmt"
	"os"
	"test/gincircl/logger/config"
	"test/gincircl/logger/internal"

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

func Zap(zapConfig *config.Zap) (logger *zap.Logger) {
	internal.LoggerConfig = *zapConfig
	if ok, _ := PathExists(zapConfig.Director); !ok { // 判断是否有Director文件夹
		fmt.Printf("create %v directory\n", zapConfig.Director)
		_ = os.Mkdir(zapConfig.Director, os.ModePerm)
	}
	levels := zapConfig.Levels()
	length := len(levels)
	cores := make([]zapcore.Core, 0, length)
	for i := 0; i < length; i++ {
		core := internal.NewZapCore(levels[i])
		cores = append(cores, core)
	}
	logger = zap.New(zapcore.NewTee(cores...))
	if zapConfig.ShowLine {
		logger = logger.WithOptions(zap.AddCaller())
	}
	return logger
}

func PathExists(path string) (bool, error) {
	fi, err := os.Stat(path)
	if err == nil {
		if fi.IsDir() {
			return true, nil
		}
		return false, errors.New("存在同名文件")
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}
